const express = require("express");
const router = express.Router();
const con = require("../db/mysql")


router.get('/', async (req, res, next) => {
  const { page, limit, state } = req.query;
  let where = "1 ";
  if (state != undefined) {
    where += `AND state=${state}`
  }
  try {
    const result = await con.query(`SELECT * FROM banner where ${where} ORDER BY id DESC LIMIT ${limit * 1} OFFSET ${(page - 1) * limit}; SELECT COUNT(*) AS total FROM banner`)
    res.json({
      msg: "查询成功",
      code: 200,
      data: result[0],
      total: result[1][0].total
    });
  } catch (error) {
    console.log(error);

  }

});

router.post('/', async (req, res, next) => {
  const { thumb, state, gid } = req.body;
  try {
    const result = await con.query(`INSERT INTO banner (thumb, state, gid) VALUES (?, ?, ?)`, [thumb, state, gid]);
    if (result.affectedRows === 1) {
      res.json({
        msg: "添加成功",
        code: 200
      });
    } else {
      res.json({
        msg: "添加失败",
        code: 500
      });
    }
  } catch (error) {
    console.log(error);
  }
});


router.delete('/:id', async (req, res) => {
  const { id } = req.params;
  try {
    await con.query(`DELETE FROM banner WHERE id=?`, id, (err, result) => {


      if (result.affectedRows === 1) {
        res.json({
          msg: "删除成功",
          code: 200
        });
      } else {
        res.json({
          msg: "删除失败",
          code: 500
        });
      }
    });
  } catch (error) {
    console.log(error);

  }

});

router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const { thumb, state, gid } = req.body;
  try {

    const result2 = await con.query(`UPDATE banner SET thumb=?,state=?,gid=?WHERE id=?`, [thumb, state, gid, id]);

    if (result2.affectedRows === 1) {
      res.json({
        msg: "更新成功",
        code: 200
      });
    } else {
      res.json({
        msg: "更新失败",
        code: 500
      });
    }

  } catch (e) {
    console.log(e);
  }

});

module.exports = router;











module.exports = router;